package com.heer.gymnasium.module.map.views;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.RatingBar;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.heer.amap.DrivingRouteOverlay;
import com.heer.amap.utils.ToastUtil;
import com.heer.gymnasium.R;
import com.heer.gymnasium.module.main.views.MainActivity;
import com.heer.gymnasium.module.map.CheckPermissionsActivity;
import com.heer.gymnasium.module.store.beans.StoreBean;
import com.heer.gymnasium.module.store.views.StoreActivity;
import com.heer.gymnasium.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by yan
 * on 2018/1/26
 * 地图展示
 */

public class MapShowActivity extends CheckPermissionsActivity implements AMapLocationListener, RouteSearch.OnRouteSearchListener {

    private static final int LAYOUT = R.layout.layout_map_show;
    private static final int MAPVIEW_ID = R.id.layout_map_show_mapv;
    private static final int STORENAME_ID = R.id.layout_map_show_storename_tv;
    private static final int RATINGBAR_ID = R.id.layout_map_show_evaluate_rbar;
    private static final int ENTER_ID = R.id.layout_map_show_enter_iv;
    private static final int RES_ID_GOTO = R.id.layout_map_show_goto_tv;

    @BindView(MAPVIEW_ID)
    MapView mapView;
    @BindView(STORENAME_ID)
    TextView nameTextView;
    @BindView(RATINGBAR_ID)
    RatingBar ratingBar;

    private StoreBean bean;
    public AMapLocationClient mLocationClient = null;
    public AMapLocationClientOption mLocationOption = null;

    private LatLonPoint mStartPoint;//起点，39.942295,116.335891
    private LatLonPoint mEndPoint;
    private ProgressDialog progDialog = null;// 搜索时进度条
    private final int ROUTE_TYPE_DRIVE = 2;
    private RouteSearch mRouteSearch;
    private AMap aMap;
    private DriveRouteResult mDriveRouteResult;

    //页面跳转 TODO：  传参应传对象，待修改。对象中包括经纬度/名称/评分
    public static void startActvity(Activity activity, StoreBean bean) {
        Intent intent = new Intent(activity, MapShowActivity.class);
        intent.putExtra(EXTRA_DATA, bean);
        activity.startActivity(intent);
    }

    private Bundle savedInstanceState;

    private CameraUpdate cameraUpdate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.savedInstanceState = savedInstanceState;

    }

    @Override
    protected void init() {
        super.init();
        setContentView(LAYOUT);
    }

    @Override
    protected void initView() {
        super.initView();
        titleUtils.setTitleText("导航");
        titleUtils.startMainActivity(this);
        mapView.onCreate(savedInstanceState);

        bean = (StoreBean) getIntent().getSerializableExtra(EXTRA_DATA);

        if (aMap == null) {
            aMap = mapView.getMap();
        }
        aMap.moveCamera(cameraUpdate);
        mRouteSearch = new RouteSearch(this);
        mRouteSearch.setRouteSearchListener(this);
        if (bean != null) {
            nameTextView.setText(bean.getStadiumname());
            ratingBar.setRating(StringUtils.toFloat(bean.getEval()));
            cameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(StringUtils.toDouble(bean.getLa()),
                    StringUtils.toDouble(bean.getLo())), 18, 0, 30));

            //绘制marker
            Marker marker = aMap.addMarker(new MarkerOptions()
                    .position(new LatLng(StringUtils.toDouble(bean.getLa()),
                            StringUtils.toDouble(bean.getLo())))
                    .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                            .decodeResource(getResources(), R.drawable.marker)))
                    .draggable(true));
            aMap.moveCamera(cameraUpdate);
            marker.showInfoWindow();
        }
    }

    @OnClick(ENTER_ID)
    public void onClick() {
        StoreActivity.startActivity(this, bean.getSid());
    }

    @OnClick(RES_ID_GOTO)
    public void onClickForGoto() {
        location();
    }

    /**
     * 启动定位
     */
    private void location() {
        mLocationOption = new AMapLocationClientOption();
        mLocationClient = new AMapLocationClient(getApplicationContext());
        mLocationClient.setLocationListener(this);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setOnceLocation(true);
        mLocationOption.setNeedAddress(true);
        if (null != mLocationClient) {
            mLocationClient.setLocationOption(mLocationOption);
            mLocationClient.stopLocation();
            mLocationClient.startLocation();
        }
        mLocationClient.setLocationOption(mLocationOption);
        mLocationClient.startLocation();
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        mStartPoint = new LatLonPoint(aMapLocation.getLatitude(), aMapLocation.getLongitude());
        mEndPoint = new LatLonPoint(StringUtils.toDouble(bean.getLa()), StringUtils.toDouble(bean.getLo()));
        searchRouteResult(RouteSearch.DrivingDefault);
    }

    /**
     * 开始搜索路径规划方案
     */
    public void searchRouteResult(int mode) {
        if (mStartPoint == null) {
            ToastUtil.show(mContext, "起点未设置");
            return;
        }
        if (mEndPoint == null) {
            ToastUtil.show(mContext, "终点未设置");
        }
        showProgressDialog();
        final RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
                mStartPoint, mEndPoint);

        RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo, mode, null,
                null, "");// 第一个参数表示路径规划的起点和终点，第二个参数表示驾车模式，第三个参数表示途经点，第四个参数表示避让区域，第五个参数表示避让道路
        mRouteSearch.calculateDriveRouteAsyn(query);// 异步路径规划驾车模式查询
    }

    /**
     * 显示进度框
     */
    private void showProgressDialog() {
        if (progDialog == null)
            progDialog = new ProgressDialog(this);
        progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progDialog.setIndeterminate(false);
        progDialog.setCancelable(true);
        progDialog.setMessage("正在搜索");
        progDialog.show();
    }

    /**
     * 隐藏进度框
     */
    private void dissmissProgressDialog() {
        if (progDialog != null) {
            progDialog.dismiss();
        }
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

    }

    @Override
    public void onDriveRouteSearched(DriveRouteResult result, int errorCode) {
        dissmissProgressDialog();
        aMap.clear();// 清理地图上的所有覆盖物
        if (errorCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getPaths() != null) {
                if (result.getPaths().size() > 0) {
                    mDriveRouteResult = result;
                    final DrivePath drivePath = mDriveRouteResult.getPaths()
                            .get(0);
                    DrivingRouteOverlay drivingRouteOverlay = new DrivingRouteOverlay(
                            mContext, aMap, drivePath,
                            mDriveRouteResult.getStartPos(),
                            mDriveRouteResult.getTargetPos(), null);
                    drivingRouteOverlay.setNodeIconVisibility(false);//设置节点marker是否显示
                    drivingRouteOverlay.setIsColorfulline(true);//是否用颜色展示交通拥堵情况，默认true
                    drivingRouteOverlay.removeFromMap();
                    drivingRouteOverlay.addToMap();
                    drivingRouteOverlay.zoomToSpan();

                } else if (result != null && result.getPaths() == null) {
                    ToastUtil.show(mContext, "对不起，没有搜索到相关数据！");
                }

            } else {
                ToastUtil.show(mContext, "对不起，没有搜索到相关数据！");
            }
        } else {
            ToastUtil.showerror(this.getApplicationContext(), errorCode);
        }


    }

    @Override
    public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

    }

    @Override
    public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

    }
}
